package com.wh.pet.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.basic.dto.PointDto;
import com.wh.basic.dto.ShopNearestUtils;
import com.wh.basic.services.IFastDfsService;
import com.wh.basic.utils.*;
import com.wh.order.mapper.OrderPetAcquisitionMapper;
import com.wh.order.pojo.OrderPetAcquisition;
import com.wh.org.dao.IEmployeeDao;
import com.wh.org.dao.ShopDao;
import com.wh.org.exception.BusinessException;
import com.wh.org.pojo.Employee;
import com.wh.org.pojo.Shop;
import com.wh.pet.dto.MsgOrderDto;
import com.wh.pet.dto.SearchMasterMsgState;
import com.wh.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.wh.pet.pojo.SearchMasterMsgAuditLog;
import com.wh.system.dao.EmployeeRoleDao;
import com.wh.user.dao.IUserDao;
import com.wh.user.pojo.LoginInfo;
import com.wh.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wh.pet.pojo.SearchMasterMsg;
import com.wh.pet.service.ISearchMasterMsgService;
import com.wh.pet.mapper.SearchMasterMsgMapper;
import com.wh.pet.dto.SearchMasterMsgDto;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IFastDfsService fastDfsService;
    @Autowired
    private ShopDao shopDao;

    @Autowired
    private MailMessageUtils mailMessageUtils;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void add(SearchMasterMsg searchMasterMsg) {
        searchMasterMsgMapper.insert(searchMasterMsg);
    }

    @Override
    public void deleteById(Long id) {
        searchMasterMsgMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void patchDel(List<Long> ids) {
        searchMasterMsgMapper.deleteBatchIds(ids);
    }

    @Override
    public void updateById(SearchMasterMsg searchMasterMsg) {
        searchMasterMsgMapper.updateById(searchMasterMsg);
    }

    @Override
    public SearchMasterMsg findOne(Long id) {
        return searchMasterMsgMapper.selectById(id);
    }

    @Override
    public List<SearchMasterMsg> findAll() {
        return searchMasterMsgMapper.selectList(null);
    }

    @Override
    public IPage<SearchMasterMsg> findByPage(SearchMasterMsgDto searchMasterMsgDto) {
        //1.创建查询条件
        QueryWrapper<SearchMasterMsg> qw = new QueryWrapper<>();
        //qw.like("xxx",searchMasterMsgDto.getXxx());
        //qw.or();
        //qw.like("xxx",searchMasterMsgDto.getXxx());
        //2.组件分页数据
        IPage<SearchMasterMsg> page = new Page<>(searchMasterMsgDto.getCurrentPage(), searchMasterMsgDto.getPageSize());
        page.setRecords(searchMasterMsgMapper.findByPage(page, qw));
        page.setTotal(searchMasterMsgMapper.selectCount(qw));
        //3.返回
        return page;
    }


    /**
     * 审核实现
     *
     * @param searchMasterMsgAuditLog
     */
    @Override
    public void auditResult(SearchMasterMsgAuditLog searchMasterMsgAuditLog) {
        //1.查询该"寻主消息"所属用户
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.selectById(searchMasterMsgAuditLog.getId());
        User user = userDao.selectById(searchMasterMsg.getUserId());
        String email = user.getEmail();

        //2.判断状态
        if (searchMasterMsgAuditLog.getState() == 0) {
            //2.1 审核->驳回
            //① 修改寻主信息的状态, 修改为-1
            searchMasterMsg.setState(SearchMasterMsgState.Reject);
            //② 发邮件
            mailMessageUtils.sendCensorSMMail(email, searchMasterMsg.getTitle(), false);
            //③ 发短信提醒(暂时无法实现,需要重新申请短信模版)
            // String phone = user.getPhone();
            // AliyunSmsUtils.sendSmsCaptcha(phone,"");
        } else {
            //2.2 审核->通过
            //① 修改寻主信息的状态. 其实修改为1
            searchMasterMsg.setState(SearchMasterMsgState.ToHandle);
            mailMessageUtils.sendCensorSMMail(email, searchMasterMsg.getTitle(), true);
        }
        //3.修改寻主信息的状态->保存到数据库
        searchMasterMsgMapper.updateById(searchMasterMsg);
        //4.存储审核日志
        searchMasterMsgAuditLogMapper.insert(searchMasterMsgAuditLog);

    }

    /**
     * 获取寻主消息分页列表
     *
     * @param searchMasterMsgDto
     * @return
     */
    @Transactional
    @Override
    public IPage<SearchMasterMsg> findPageByState(SearchMasterMsgDto searchMasterMsgDto, HttpServletRequest request) {
        //1.创建查询条件
        QueryWrapper<SearchMasterMsg> qw = new QueryWrapper<>();
        //2。获取登录信息
        LoginInfo logininfo = LoginContext.getLogininfo(request);
        //3.判断身份，如果是用户查询，只能查询自己的信息
//        if (logininfo.getType() != 0) {
//            User user = userDao.selectOne(new QueryWrapper<User>().eq("logininfo_id", logininfo.getId()));
//            if (user != null) {
//                qw.eq("user_id", user.getId());
//            }
//        } else {
//            //4 如果是管理员，只能查管理员个人信息
//            Employee employee = employeeDao.selectOne(new QueryWrapper<Employee>().eq("logininfo_id", logininfo.getId()));
//            //5.判断身份, 是否是店铺管理员, 如果是只能查询当前店铺信息
//            if (employee.getShopId() != null) {
//                qw.eq("shop_id", employee.getShopId());
//            }
//        }

        //6.添加状态条件(未审核/待处理/已完成/寻主池)

        if (searchMasterMsgDto.getState() != null) {
            qw.eq("state", searchMasterMsgDto.getState());
        }
        //7.添加模糊查询条件
        String keyword = searchMasterMsgDto.getKeyword();
        if (ObjectUtil.isNotEmpty(keyword)) {
            qw.and(sql -> {
                sql.like("title", keyword);
                sql.or();
                sql.like("name", keyword);
                sql.or();
                sql.like("address", keyword);
                sql.or();
                sql.like("coat_color", keyword);
            });

        }
        //8.组件分页数据
        IPage<SearchMasterMsg> page = new Page<>(searchMasterMsgDto.getCurrentPage(), searchMasterMsgDto.getPageSize());
        page.setRecords(searchMasterMsgMapper.findByPage(page, qw));
        page.setTotal(searchMasterMsgMapper.selectCount(qw));
        return page;
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        //一旦拒单，就直接放入寻主池中
        UpdateWrapper<SearchMasterMsg> uw = new UpdateWrapper<>();
        uw.set("state", 3);
        uw.set("shop_id", null);
        uw.eq("id", id);
        searchMasterMsgMapper.update(null, uw);
    }

    /*
    管理员点击接单操作
     */
    @Override
    public void accept(MsgOrderDto msgOrderDto) {
        //1.校验当前消息是否在处理
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.selectList(new QueryWrapper<OrderPetAcquisition>().eq("search_master_msg_id", msgOrderDto.getMsgId()));
        //1.1 如果查询到数据，说明该寻主消息被处理过
        if (orders != null && orders.size() > 0) {
            //1.2 遍历每条处理消息
            for (OrderPetAcquisition order : orders) {
                //1.3 判断订单状态==0，说明该订单正在处理或已经处理完成。直接停止。
                if (order != null && order.getState() == 0) {
                    throw new BusinessException("订单正在处理或已经处理完成");
                }
            }
        }


        //2.如果该寻主消息没被处理过，或不是正在处理，都可以生成收购订单
        //2.1 获取寻主详细消息
        SearchMasterMsg msg = searchMasterMsgMapper.selectById(msgOrderDto.getMsgId());
        //2.2 生成订单对象
        OrderPetAcquisition newOrder = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        newOrder.setOrderSn(orderSn);
        newOrder.setDigest(msgOrderDto.getNote());
        //最后确认时间(3天后)
        newOrder.setLastcomfirmtime(LocalDateTime.now().plusDays(3));
        newOrder.setState(0);//待处理
        newOrder.setPrice(msg.getPrice());
        //order.setPaytype();//支付类型(只是分配人员去接受宠物，并没有接收，所以没有支付类型)
        //order.setPetId();//宠物id
        newOrder.setUserId(msg.getUserId());
        newOrder.setShopId(msg.getShopId());
        newOrder.setAddress(msg.getAddress());
        newOrder.setEmpId(msgOrderDto.getHandler());
        newOrder.setSearchMasterMsgId(msg.getId());
        orderPetAcquisitionMapper.insert(newOrder);

        //3.通知处理人去接宠物
        Employee employee = employeeDao.selectById(msgOrderDto.getHandler());
        //SmsUtil.sendMsg(employee.getPhone(),"你有新的订单，请在3之内去" + newOrder.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在3之内去" + newOrder.getAddress() + "接回宠物");
    }


    /**
     * 发布寻主信息
     *
     * @param searchMasterMsg
     * @param request
     */

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //1.百度AI智能审核
        //1.1 审核标题
        Boolean aBoolean = BaiduAuditUtils.TextCensor(searchMasterMsg.getTitle());
        if (!aBoolean) {
            throw new BusinessException("标题违规,请检查后重试!");
        }
        //1.2 审核图片
        String resources = searchMasterMsg.getResources();
        if (resources != null) {
            String[] imgUrls = resources.split(",");
            for (String imgUrl : imgUrls) {
                byte[] bytes = fastDfsService.downloadFile(imgUrl);
                Boolean imgCensor = BaiduAuditUtils.ImgCensor(bytes);
                if (!imgCensor) {
                    throw new BusinessException("图片违规,请检查后重试!");
                }
            }
        }

        //2.获取登录人id
        LoginInfo logininfo = LoginContext.getLogininfo(request);
        User user = userDao.selectOne(new QueryWrapper<User>().eq("logininfo_id", logininfo.getId()));

        //3.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
        //3.1 计算自身坐标
        PointDto point = BaiduMapUtils.getPoint(searchMasterMsg.getAddress());
        //3.2 计算最近店铺
        Shop shop = ShopNearestUtils.getNearestShop(point, shopDao.selectList(null));
        //3.3 判断是否找到最近店铺
        if (shop != null) {
            //4.4 把最近店铺添加到寻主信息中
            searchMasterMsg.setState(SearchMasterMsgState.ToAudit);
            searchMasterMsg.setShopId(shop.getId());
        } else {
            searchMasterMsg.setState(SearchMasterMsgState.SearchPool);
        }

//    //   4.将寻主消息添加到数据库
//         searchMasterMsg.setUserId(user.getId());
//         searchMasterMsgMapper.insert(searchMasterMsg);
    }
}
